package com.hmsg.health.utils;

import java.security.AlgorithmParameters;
import java.security.Key;
import java.security.SecureRandom;
import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * @author LuJunQiao
 * @version 2017年5月16日 下午3:12:34
 * @since 1.0.0
 * @Description aes加密解密:AES-128-CBC，数据采用PKCS#7填充。
 */
public class AESUtil {
	// 算法名
	public static final String KEY_ALGORITHM = "AES";
	// 加解密算法/模式/填充方式
	// ECB模式只用密钥即可对数据进行加密解密，CBC模式需要添加一个参数iv
	public static final String CIPHER_ALGORITHM = "AES/CBC/PKCS7Padding";
	static {
		// 开启AES/CBC/PKCS7Padding支持
		Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
	}

	// 生成密钥
	public static byte[] generateKey() throws Exception {
		Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
		KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_ALGORITHM);
		keyGenerator.init(128);
		SecretKey key = keyGenerator.generateKey();
		return key.getEncoded();
	}

	// 生成iv
	public static AlgorithmParameters generateIV() throws Exception {
		// iv 为一个 16 字节的数组
		byte[] iv = new SecureRandom().generateSeed(16);
		AlgorithmParameters params = AlgorithmParameters.getInstance(KEY_ALGORITHM);
		params.init(new IvParameterSpec(iv));
		return params;
	}

	// 转化成JAVA的密钥格式
	public static Key convertToKey(byte[] keyBytes) throws Exception {
		SecretKey secretKey = new SecretKeySpec(keyBytes, KEY_ALGORITHM);
		return secretKey;
	}

	// 加密
	public static byte[] encrypt(byte[] data, byte[] keyBytes, AlgorithmParameters iv) throws Exception {
		// 转化为密钥
		Key key = convertToKey(keyBytes);
		Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
		// 设置为加密模式
		cipher.init(Cipher.ENCRYPT_MODE, key, iv);
		return cipher.doFinal(data);
	}

	// 解密
	public static byte[] decrypt(byte[] encryptedData, byte[] keyBytes, byte[] ivBytes) throws Exception {
		AlgorithmParameters params = AlgorithmParameters.getInstance(KEY_ALGORITHM);
		params.init(new IvParameterSpec(ivBytes));
		return decrypt(encryptedData, keyBytes, params);
	}

	// 解密
	public static byte[] decrypt(byte[] encryptedData, byte[] keyBytes, AlgorithmParameters iv) throws Exception {
		Key key = convertToKey(keyBytes);
		Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
		// 设置为解密模式
		cipher.init(Cipher.DECRYPT_MODE, key, iv);
		return cipher.doFinal(encryptedData);
	}
}
